import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author zhangkaiqiang
 * @Date 2020/7/20 18:05
 * @Version 1.0
 *
 * Socket 服务端实例
 */
public class EchoServer {

    private  ServerSocket serverSocket;

    private final Integer prot=8081;

    /**
     * 无参构造初始化方法
     */
    public EchoServer (){}


    /**
     * 建立连接
     */
    public void init(){
        try {
            serverSocket=new ServerSocket(prot);
            Socket socket = serverSocket.accept();
            handlerAccept(socket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 处理客户端连接
     * @param socket
     */
    public void handlerAccept(Socket socket){
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            byte[] buffer=new byte[1024];
            int n;
            while ((n= inputStream.read(buffer))>0) {
                outputStream.write(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        EchoServer server=new EchoServer();
        server.init();
    }
}
